<?php

namespace App\Http\Middleware;

use App\Services\SecurityService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SecurityMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 检查是否为可疑请求
        if (SecurityService::isSuspiciousRequest($request)) {
            SecurityService::logSecurityEvent('Blocked suspicious request');
            return response()->json([
                'success' => false,
                'message' => '请求被拒绝',
            ], 400);
        }

        // 检查请求频率限制
        $rateLimitKey = 'api:' . $request->path() . ':' . $request->ip();
        if (!SecurityService::checkRateLimit($rateLimitKey, 100, 1)) {
            return response()->json([
                'success' => false,
                'message' => '请求过于频繁，请稍后再试',
            ], 429);
        }

        // 清理输入数据
        if ($request->isMethod('POST') || $request->isMethod('PUT') || $request->isMethod('PATCH')) {
            $sanitizedData = SecurityService::sanitizeInput($request->all());
            $request->merge($sanitizedData);
        }

        // 添加安全头
        $response = $next($request);
        
        $response->headers->set('X-Content-Type-Options', 'nosniff');
        $response->headers->set('X-Frame-Options', 'DENY');
        $response->headers->set('X-XSS-Protection', '1; mode=block');
        $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
        $response->headers->set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');

        return $response;
    }
}
